/*
 * CS340 fatboys
 */
package fatboy.addons;

import junit.framework.Assert;
import fatboy.hypeerweb.Node;

/*
 * @author James
 * 
 */
/**
 * The Visitor SendMessage.
 * @author James
 * @domain Valid MessageData
 */
public class SendMessage implements Visitor{
	
	private static final long serialVersionUID = -2573757035877895985L;

	/**
	 * @param sender the root/source node
	 * @param recipient the node to receive the message
	 * @param msg the command being sent 
	 * 
	 * @pre true
	 * @post 
	 */
	public void sendMessage(Node sender, Node recipient, Object msg){
		Assert.assertTrue(msg instanceof Visitor);
		
		sender.accept(this, new MessageData((Visitor)msg,recipient));
	}

	/**
	 * @param thisNode , the source node
	 * @param command , the command to execute on the node
	 * 
	 * @pre 
	 * @post 
	 */
	public void visit(Node thisNode, Object messageData) {
		Assert.assertTrue(messageData instanceof MessageData); 
		MessageData data = (MessageData)messageData;
		if (thisNode.equals(data.getTarget())) {
			//data.getCommand()
			//execute command    			
			//Do message
			System.out.println("Executing message at "+ thisNode.getAddress());
			data.getCommand().visit(thisNode, data.getCommand());
			
			return;
		}
		
		System.out.println("Sending message from "+ thisNode.getAddress() 
				+ " to "+data.getTarget().getAddress());
		
		Node target = thisNode.getNodeAt(data.getTarget().getAddress());
		target.accept(this, messageData);
		
	}

}
